/*
** get_passwd.c for get_passwd in /home/comet_a//afs/local/sys_unix/my_select/ex_2
** 
** Made by alexandre comet
** Login   <comet_a@epitech.net>
** 
** Started on  Fri Jan 13 13:25:55 2012 alexandre comet
** Last update Fri Jan 13 18:37:34 2012 alexandre comet
*/

#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

void	my_putchar(char c)
{
  write(1, &c, 1);
}

void	my_putstr(char *str)
{
  int	i;

  i = 0;
  while (str[i])
    my_putchar(str[i++]);
}

int	test(struct termios *t)
{
  if (tcgetattr(0, t) == -1)
    {
      fprintf(stderr, "tcgetattr failed\n");
      return (1);
    }
  t->c_lflag &= ~ICANON;
  t->c_lflag &= ~ECHO;
  t->c_cc[VMIN] = 1;
  t->c_cc[VTIME] = 0;
  if (tcsetattr(0, 0, t) == -1)
    {
      fprintf(stderr, "tcsetattr failed\n");
      return (1);
    }
  return (0);
}

int	       react_echo(struct termios *t)
{
  t->c_lflag |= ECHO; //activation
  if (tcsetattr(0, 0, t) == -1)
    {
      fprintf(stderr, "tcsetattr failed\n");
      return (1);
    }
  return (0);
}

int	main()
{
  struct termios	save;
  char			*str;
  int			i;

  i = 0;
  str = malloc(sizeof(*str));
  if (str == NULL)
    return (1);
  test(&save);
  my_putstr("Enter your password : ");
  while (read(0, &str[i], 1) && str[i] != '\n')
    {
      my_putchar('*');
      i++;
    }
  my_putstr("\nYour password is : ");
  my_putstr(str);
  react_echo(&save);
  return (0);
}
